package cn.gcjxsc.payment.service.wx;

import cn.gcjxsc.common.consts.RedPackType;
import cn.gcjxsc.common.data.notify.redpack.RedPackData;
import cn.gcjxsc.common.data.wx.redpack.SendResponse;
import cn.gcjxsc.common.util.validator.BindResult;
import cn.gcjxsc.payment.data.RedPackCert;
import cn.gcjxsc.payment.data.RedPackConfig;
import cn.gcjxsc.payment.data.WeChatConfig;
import cn.gcjxsc.payment.data.wx.redpack.SendData;
import cn.gcjxsc.payment.entity.wx.RedPackRecord;
import cn.gcjxsc.payment.util.WxUtil;
import com.zgxl.common.util.DateTimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.io.IOException;
import java.util.Set;

/**
 * 微信红包业务
 * @author pumbaa
 * @since 1.0
 */
@Service
public class RedPackService {
    @Autowired
    private WeChatApiService apiService;
    @Autowired
    private RedPackRecordService redPackRecordService;
    @Autowired
    private ResourceLoader resourceLoader;

//    private static String certPath;
    @Autowired
    private RedPackCert redPackCert;

    /**
     * 检查数据是否有效
     * @param data 红包数据
     * @param bindResult 检验结果
     * @return
     */
    public boolean checkInputData(RedPackData data, BindResult bindResult) {
        Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
        Set<ConstraintViolation<RedPackData>> validate = validator.validate(data);
        if (validate.size() > 0) {
            bindResult.setErrorMsg(validate.iterator().next().getMessage());
            bindResult.setErrorCount(validate.size());
            return false;
        }
        return true;
    }

    public RedPackRecord findBySnAndType(String sn, Integer type) {
        return redPackRecordService.findBySnAndType(sn, type);
    }

    /**
     * 保存红包记录
     * @param record 红包数据
     * @return
     */
    @Transactional
    public RedPackRecord saveRedPackRecord(RedPackRecord record) {
        return redPackRecordService.saveOrUpdate(record);
    }
    @Transactional
    public RedPackRecord updateRedPackRecord(RedPackRecord record) {
        return redPackRecordService.saveOrUpdate(record);
    }

    public SendData prepareSendData(RedPackRecord record, RedPackConfig config) {
        SendData sendData = new SendData();
        sendData.setActName("购物回馈红包");
        sendData.setAmount(record.getAmount());
        sendData.setOpenid(record.getOpenid());
        sendData.setRemark(record.getType() == RedPackType.BUY.getType() ? "购物回馈红包" :"分享回馈红包");
        sendData.setStoreName(record.getStoreName());
        sendData.setWishing(config.getWishing());
        sendData.setTradeNo(record.getTradeNo());

        return sendData;
    }


    public SendResponse sendRedPack(WeChatConfig config, SendData sendData, BindResult bindResult) {
        try {
            return apiService.sendRedPack(config, sendData, redPackCert.getFile());
        } catch (Exception e) {
            e.printStackTrace();
            bindResult.setErrorMsg("发送红包失败.[" + e.getMessage() + "]");
            return null;
        }
    }
//
//    private String getCertPath(){
//        if (null == certPath) {
//            Resource resource = resourceLoader.getResource("classpath:/certs/apiclient_cert.p12");
//            try {
//                certPath = resource.getFile().getAbsolutePath();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//        return certPath;
//    }

    /**
     * 红包是否发送成功
     * @param sendResponse 发送结果
     * @return
     */
    public boolean isRedPackSendSuccess(SendResponse sendResponse) {
        return sendResponse.getReturn_code().equalsIgnoreCase(WxUtil.SUCCESS) && sendResponse.getResult_code().equalsIgnoreCase(WxUtil.SUCCESS);
    }

    public String createTradeNo(String prefix) {
        String s = DateTimeUtil.generateSn();
        int max = 28-s.length()-prefix.length();
        StringBuilder sb = new StringBuilder();
        for (int i=0;i<max;i++) {
            sb.append((int)(Math.random()*10));
        }
        return prefix+s+sb.toString();
    }
}
